#include <iostream>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void ChildWrite(int wfd)
{
    char buffer[1024] = {0};
    //int cnt = 10;
    int cnt = 0;
    while (true)
    {
        snprintf(buffer, sizeof(buffer), "i am child: pid->%d, cnt->%d", getpid(), cnt++);
        write(wfd, buffer, strlen(buffer));
        sleep(1);
    }
}

void FatherRead(int rfd)
{
    char buffer[1024] = {0};
    int cnt = 5;
    while (cnt--)
    {
        // sleep(5);
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "child say:" << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "n:" << n << std::endl;
            sleep(1);
        }
    }
}

int main()
{
    // 1.打开管道文件,一般fds[0]:read, fds[1]:write
    int fds[2] = {0};
    int n = pipe(fds);
    // std::cout << "fds[0]:" << fds[0] << std::endl;
    // std::cout << "fds[1]:" << fds[1] << std::endl;

    if (n < 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }

    // 2.创建子进程并构建单向通信信道->father r, child w
    pid_t id = fork();
    if (id == 0)
    {
        // child
        close(fds[0]);

        // operate
        ChildWrite(fds[1]);
        close(fds[1]);
        exit(1);
    }

    // father
    close(fds[1]);

    // operate
    FatherRead(fds[0]);

    // 关闭读端
    close(fds[0]);

    int status = 0;
    waitpid(id, &status, 0);
    std::cout << "exit code->" << ((status >> 8) & 0xFF) << "exit signal->" << (status & 0x7F) << std::endl;

    return 0;
}